package com.hmjk.health.home;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hmjk.health.HealthApp;
import com.hmjk.health.FocusFragment;
import com.hmjk.health.IndexActivity;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.DEV_FACE;
import com.hmjk.health.util.TODO_DATA;
import com.hmjk.health.views.BatteryView;
import com.hmjk.health.views.InnerListView;
import com.hmjk.health.views.RefreshLayout;
import com.hmjk.health.views.RefreshLayout.OnRefreshListener;
import com.hmjk.health.views.RoundImageView;

public class AccountFragment extends FocusFragment implements OnClickListener{
	private final String TAG = AccountFragment.class.getSimpleName();
	private HealthApp mApp = null;
	private ImageView scanView;
	private RefreshLayout refresh;
	private JSONObject mData;	
	private ArrayList<DEV_DATA> mDevListData = new ArrayList<DEV_DATA>();
	
	private RoundImageView mPic;
	private ImageView mLvBar;
	private TextView mLvTxt;
	//private TextView mLvHint;
	private TextView mNick;
	private TextView mAccount;
	private TextView mDevNum;
	
	private TextView mDevRoomHint;
	private LinearLayout mDevRoom;
	private HorizontalScrollView mDevScroll;
	private TextView mToDoNum;
	private TextView mToDoEmpty;
	private InnerListView mToDoList;
	private ToDoListAdapter mToDoAdapter;
	
	private long uptime = 0;
	private LayoutInflater mInflater;

	private float density;
	private boolean attached = false;
	private String entertype = null;
	
	private void logd(String info){
		Log.d(TAG,info);
	}
	
	@Override
	public void onAttach(Activity a){
		logd("onAttach");
		super.onAttach(a);
		attached = true;
	}
	
	@Override
	public void onDetach(){
		logd("onDetach");
		attached = false;
		super.onDetach();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
		mApp = (HealthApp)getActivity().getApplication();
		mInflater = inflater;
		entertype = mApp.getEnterType();
		
		density = getResources().getDisplayMetrics().density;
		View v = inflater.inflate(R.layout.account, container, false);
		
		ImageView ticon = (ImageView) v.findViewById(R.id.title_icon);
		TextView ttext = (TextView) v.findViewById(R.id.title_text);
		
		scanView = (ImageView) v.findViewById(R.id.scan);
		if(entertype.equals(IndexActivity.ENTER_HEALTH)){
			ticon.setImageResource(R.drawable.health_logo);
			ttext.setTextColor(getResources().getColor(R.color.FOREGROUND_RED));
			ttext.setText(R.string.health_name);
			scanView.setImageResource(R.drawable.health_scan_scan);
		}
		scanView.setOnClickListener(this);
		
		View mydata = v.findViewById(R.id.myname);
		mydata.setOnClickListener(this);
		
		ImageView setv = (ImageView) v.findViewById(R.id.set);
		if(entertype.equals(IndexActivity.ENTER_HEALTH)){
			setv.setImageResource(R.drawable.health_set_icon);
		}
		setv.setOnClickListener(this);
		
		refresh = (RefreshLayout)v.findViewById(R.id.refresh_root);
		if(entertype.equals(IndexActivity.ENTER_HEALTH)){
			refresh.setTheme(RefreshLayout.THEME_HEALTH);
		}
		//ScrollView scv = (ScrollView)refresh.findViewById(R.id.refresh_scroll);
		refresh.initScroll();
		refreshing = null;
		refresh.setOnRefreshListener(new OnRefreshListener(){

			@Override
			public void onRefresh() {
				refreshing = null;
				boolean ok = mApp.getDataManager().refreshData(DataManager.F_USERDATA);
				if(ok){
					refreshing = new String(DataManager.F_USERDATA);
				}
				ok = mApp.getDataManager().refreshData(DataManager.F_USERFACE);
				if(ok){
					if(refreshing == null)
						refreshing = new String(DataManager.F_USERFACE);
					else
						refreshing += ":" + DataManager.F_USERFACE;
				}
				
				ok = mApp.getDataManager().refreshData(DataManager.F_DEVICELIST);
				if(ok){
					if(refreshing == null)
						refreshing = new String(DataManager.F_DEVICELIST);
					else
						refreshing += ":" + DataManager.F_DEVICELIST;
				}
				
				ok = mApp.getDataManager().refreshData(DataManager.F_DEVICEFACE);
				if(ok){
					if(refreshing == null)
						refreshing = new String(DataManager.F_DEVICEFACE);
					else
						refreshing += ":" + DataManager.F_DEVICEFACE;
				}	
				if(refreshing == null){
					Message m = mhandler.obtainMessage(MSG_CLOSE_REFRESH_VIEW);
					mhandler.sendMessageDelayed(m, 500);
				}
			}
			
		});
		
		mPic = (RoundImageView)v.findViewById(R.id.photo);
		mLvBar = (ImageView)v.findViewById(R.id.data_lv);
		mLvTxt = (TextView)v.findViewById(R.id.data_lv_txt);
		//View myData = v.findViewById(R.id.my_data);
		//myData.setOnClickListener(this);
		
		//mLvHint = (TextView)v.findViewById(R.id.data_hint);
		mNick = (TextView)v.findViewById(R.id.nick);
		if(entertype.equals(IndexActivity.ENTER_HEALTH)){
			mNick.setTextColor(getResources().getColor(R.color.FOREGROUND_RED));
		}
		mAccount = (TextView)v.findViewById(R.id.account);
		
		mDevNum = (TextView)v.findViewById(R.id.looked_num);
		mDevNum.setText("(0)");
		mDevRoomHint = (TextView)v.findViewById(R.id.lookDevHint);
		mDevRoomHint.setText(R.string.Loading);
		
		mDevRoom = (LinearLayout)v.findViewById(R.id.lookDevRoom);
		mDevScroll = (HorizontalScrollView) v.findViewById(R.id.devScroll);
		mDevScroll.setOnTouchListener(new View.OnTouchListener(){
			private float beginX = -1;
			private int go = 0;
			
			@Override
			public boolean onTouch(View v, MotionEvent ev) {
				View child = mDevScroll.getChildAt(0);
				int totolWidth = child.getMeasuredWidth();
				int seeWidth = mDevScroll.getMeasuredWidth();
				if(ev.getAction() == MotionEvent.ACTION_MOVE) {	
					int height = totolWidth - seeWidth;
					int scrollX = mDevScroll.getScrollX();
					float x = ev.getX();
					if(beginX == -1){
						go = 0;
						beginX = x;
					}
					
					if((x - beginX) > (10 * density)){
						//-->
						if(scrollX <= 0){
							//logd("mDevScroll header");
							go = -1;
						}else{
							go = 0;
							beginX = x;
						}
					}else if((beginX - x) > (10 * density)){
						if(scrollX >= height){
							//logd("mDevScroll tail");
							go = 1;
						}else{
							go = 0;
							beginX = x;
						}
					}else{
						go = 0;
						beginX = x;
					}
				}else if(ev.getAction() == MotionEvent.ACTION_DOWN){
					beginX = ev.getX();
					go = 0;
				}else if((ev.getAction() == MotionEvent.ACTION_UP) 
							|| (ev.getAction() == MotionEvent.ACTION_CANCEL)){
					beginX = -1;
					if(go == 1){
						((BaseHomeActions)getActivity()).moveToNext();
					}else if(go == -1){
						((BaseHomeActions)getActivity()).moveToPre();
					}
					go = 0;
				}
				return false;
			}
			
		});
		
		mToDoNum = (TextView)v.findViewById(R.id.todo_count);
		mToDoEmpty = (TextView)v.findViewById(R.id.todoEmpty);
		mToDoList = (InnerListView)v.findViewById(R.id.todo_list);
		mToDoAdapter = new ToDoListAdapter(getActivity());
		mToDoList.setAdapter(mToDoAdapter);
		mToDoList.setOnItemClickListener(new AdapterView.OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View v,
					int pos, long arg3) {
				ArrayList<TODO_DATA> arr = ((HomeActivity)getActivity()).getToDoArray();
				if(arr == null)
					return;
				
				if(arr.size() == 0)
					return;
				
				TODO_DATA e = arr.get(pos);
				
				//ToDoListAdapter.ViewHolder h = (ToDoListAdapter.ViewHolder) v.getTag();
				((BaseHomeActions)getActivity()).openToDoActivity(e);
				
			}
			
		});
		
		return v;
	}
	
	class ToDoListAdapter extends BaseAdapter{
		private Context mContext;
		
		class ViewHolder{
			public TextView info;
			public TextView timedate;
			//public String showinfo;
		}
		
		public ToDoListAdapter(Context context){
			mContext = context;
		}
		
		@Override
		public int getCount() {
			ArrayList<TODO_DATA> arr = ((HomeActivity)getActivity()).getToDoArray();
			if(arr == null)
				return 0;
			
			return arr.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		private String getToDoInfo(String code, String uid, String tid, String fid,JSONObject mark){
			if(code.equals("0201")){
				String[] fargs = new String[1];
				fargs[0] = fid;
				JSONObject fajson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYLIST, fargs);
				String familyname = null;
				if(fajson != null){
					try {
						familyname = fajson.getString("name");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						familyname = null;
					}
				}
				
				if(familyname == null){
					familyname = getResources().getString(R.string.noFaName);
				}else if(familyname.length() > 10){
					familyname = familyname.substring(0, 10)+"...";
				}
				
				String user = null;
				try {
				if(mark != null){
					if(mark.has("nickname")){
						user = mark.getString("nickname");
					}
					if((user == null) || (user.trim().length() == 0)){
						if(mark.has("username")){
							user = mark.getString("username");
						}
					}
				}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				if((user == null) || (user.trim().length() == 0)){
					user = getResources().getString(R.string.noName);
				}
				return getResources().getString(R.string.todo_join_family, user,familyname);
			}else if(code.equals("0601")){
				//invitation to tid
				String msg = getResources().getString(R.string.none);
				try {
					if(mark != null){
						if(mark.has("username")){
							msg = mark.getString("username");
						}
					}
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				return getResources().getString(R.string.todo_invitation_by_dev, msg);
			}else{
				String devname = null;
				for(DEV_DATA d:mDevListData){
					if(d.id.equals(tid)){
						devname = d.name;
					}
				}
				if(devname == null){
					devname = getResources().getString(R.string.noName);
				}
				
				if(code.equals("0301")){
					/*
					String[] uargs = new String[1];
					uargs[0] = uid;
					JSONObject ujson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_FAMILYMEMBER, uargs);
					String username = null;
					if(ujson != null){
						try {
							username = ujson.getString("name");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							username = null;
						}
					}
					*/
					
					String user = null;
					try {
					if(mark != null){
						if(mark.has("nickname")){
							user = mark.getString("nickname");
						}
						if((user == null) || (user.trim().length() == 0)){
							if(mark.has("username")){
								user = mark.getString("username");
							}
						}
					}
					} catch (JSONException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					
					if(user == null){
						user = getResources().getString(R.string.noFaName);
					}
					return getResources().getString(R.string.todo_interest_dev, user, devname);
				}else if(code.equals("0401")){
					return getResources().getString(R.string.todo_dev_overfence, devname);
				}else if(code.equals("0402")){
					return getResources().getString(R.string.todo_dev_powerlow, devname);
				}else if(code.equals("0403")){
					return getResources().getString(R.string.todo_dev_simchange, devname);
				}else if(code.equals("0404")){
					return getResources().getString(R.string.todo_dev_frozen, devname);
				}
			}
			return null;
		}
		
		private String getTimeString(long ltime){
			Time time = new Time();
			time.setToNow();
			int year = time.year;
			int yearday = time.yearDay;
			
			time.set(ltime);
			
			String datestr;
			
			if(time.year == year && time.yearDay == yearday){
				datestr = getResources().getString(R.string.addr_today);
			}else if(time.year == year && time.yearDay == (yearday-1)){
				datestr = getResources().getString(R.string.addr_yesterday);
			}else{
				datestr = String.format("%04d-%02d-%02d", time.year,time.month+1,
					time.monthDay);
			}
			String timestr = String.format("%02d:%02d", time.hour, time.minute);
			
			return datestr+" "+timestr;
		}

		@Override
		public View getView(int pos, View itemView, ViewGroup group) {
			ViewHolder holder;
			
			if(itemView == null){
				LayoutInflater inflater = LayoutInflater.from(mContext);
				itemView = inflater.inflate(R.layout.todo_list_item, null);
				holder = new ViewHolder();
				
				holder.info = (TextView)itemView.findViewById(R.id.item_info);
				holder.timedate = (TextView)itemView.findViewById(R.id.item_time);
				
				itemView.setTag(holder);
			}else{
				holder = (ViewHolder)itemView.getTag();
			}
			
			try {
				ArrayList<TODO_DATA> arr = ((HomeActivity)getActivity()).getToDoArray();
				TODO_DATA e = arr.get(pos);
				
				JSONObject mark = null;
				if((e.mark != null) && (e.mark.trim().length() > 0)){
					mark= new JSONObject(e.mark);
				}
				
				String showinfo = getToDoInfo(e.code,e.uid,e.tid,e.fid,mark);
				holder.info.setText(showinfo);
				
				String timestr = getTimeString(e.time);
				holder.timedate.setText(timestr);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
					
			return itemView;
		}
		
	}
	
	
	private void updateData(){
		if(mApp == null)
			return;
		retrieveUserData();
		retrieveDeviceListData();
	}
	
	public void updateTODO(){
		if(!attached)
			return;
		
		int size = 0;
		
		ArrayList<TODO_DATA> arr = ((HomeActivity)getActivity()).getToDoArray();
		
		if(arr != null){
			size = arr.size();
		}
		
		((BaseHomeActions)getActivity()).setAccountButtonNum(size);
		if(size > 0){
			mToDoNum.setVisibility(View.VISIBLE);
			if(size > 99){
				mToDoNum.setText("99+");
			}else{
				mToDoNum.setText(""+size);
			}
			mToDoEmpty.setVisibility(View.GONE);
			mToDoList.setVisibility(View.VISIBLE);
			mToDoList.setFocusable(false);
			mToDoAdapter.notifyDataSetChanged();
		}else{
			mToDoNum.setVisibility(View.INVISIBLE);
			mToDoEmpty.setVisibility(View.VISIBLE);
			mToDoList.setVisibility(View.GONE);
		}
	}
	
	private final int MSG_CLOSE_REFRESH_VIEW = 111;
	
	private Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case MSG_CLOSE_REFRESH_VIEW:{
				cancelRefresh();
			}
			break;
			}
		}
	};
	
	private String[] getTIDS(ArrayList<DEV_DATA> list){
		if(list == null)
			return null;
		
		int size = list.size();
		if(size == 0)
			return null;
		
		String[] ret = new String[size];
		int pos = 0;
		for(DEV_DATA d:list){
			ret[pos] = new String(d.id);
			pos ++;
		}
		return ret;
	}
	
	private void setDataLevelViews(int lev){
		if(lev >= 5){
			mLvTxt.setText(R.string.dlv_high);
			if(entertype.equals(IndexActivity.ENTER_HEALTH)){
				mLvBar.setImageResource(R.drawable.health_dlv_full);
				mLvTxt.setTextColor(getResources().getColor(R.color.HEALTH_DLV_HIGH));
			}else{
				mLvBar.setImageResource(R.drawable.dlv_full);
				mLvTxt.setTextColor(getResources().getColor(R.color.DLV_HIGH));
			}
			//mLvHint.setVisibility(View.INVISIBLE);
		}else if(lev >= 4){
			mLvTxt.setText(R.string.dlv_high);
			if(entertype.equals(IndexActivity.ENTER_HEALTH)){
				mLvBar.setImageResource(R.drawable.health_dlv_high);
				mLvTxt.setTextColor(getResources().getColor(R.color.HEALTH_DLV_HIGH));
			}else{
				mLvBar.setImageResource(R.drawable.dlv_high);
				mLvTxt.setTextColor(getResources().getColor(R.color.DLV_HIGH));
			}
			//mLvHint.setVisibility(View.INVISIBLE);
		}else if(lev >= 3){
			mLvBar.setImageResource(R.drawable.dlv_mid_more);
			mLvTxt.setText(R.string.dlv_mid);
			mLvTxt.setTextColor(getResources().getColor(R.color.DLV_MID));
			//mLvHint.setVisibility(View.INVISIBLE);
		}else if(lev >= 2){
			mLvBar.setImageResource(R.drawable.dlv_mid);
			mLvTxt.setText(R.string.dlv_mid);
			mLvTxt.setTextColor(getResources().getColor(R.color.DLV_MID));
			//mLvHint.setVisibility(View.INVISIBLE);
		}else if(lev >= 1){
			mLvBar.setImageResource(R.drawable.dlv_low);
			mLvTxt.setText(R.string.dlv_low);
			mLvTxt.setTextColor(getResources().getColor(R.color.DLV_LOW));
			//mLvHint.setVisibility(View.VISIBLE);
		}else{
			mLvBar.setImageResource(R.drawable.dlv_ex_low);
			mLvTxt.setText(R.string.dlv_low);
			mLvTxt.setTextColor(getResources().getColor(R.color.DLV_LOW));
			//mLvHint.setVisibility(View.VISIBLE);
		}
	}
	
	private void updateDevList(){
		if(!attached)
			return;
		
		int looksize = mDevListData.size();
		mDevNum.setText("( "+looksize+" )");
		if(looksize == 0){
			mDevRoomHint.setVisibility(View.VISIBLE);
			mDevRoomHint.setText(R.string.DevListEmpty);
			mDevScroll.setVisibility(View.INVISIBLE);
		}else{
			//sortShownList();
			mDevScroll.setVisibility(View.VISIBLE);
			mDevRoomHint.setVisibility(View.INVISIBLE);
			updateDevRooms();
		}
	}
	
	private void updateDevFaceOnly(String tid){
		if(!attached)
			return;
		
		int size = mDevRoom.getChildCount();
		if(size > 0){
			for(int i = 0; i< size; i++){
				View v = mDevRoom.getChildAt(i);
				View item = v.findViewById(R.id.item_view);
				DEV_DATA d = (DEV_DATA) item.getTag();
				if(d.id.equals(tid)){
					DEV_FACE f = null;
					HashMap<String,DEV_FACE> faceMap = (HashMap<String, DEV_FACE>) mApp.getDataManager().checkData(DataManager.F_DEVICEFACE, null);
					if(faceMap != null){
						f = faceMap.get(tid);
					}
					ImageView icon = (ImageView)v.findViewById(R.id.dev_pic);
					if((f != null) && (f.bitmap != null)){
						if(f.bitmap.isRecycled()){
						logd("DEV_FACE " + f.tid + " is recycled");
						icon.setImageResource(R.drawable.dev_default_pic);
						}else{
						icon.setImageBitmap(f.bitmap);
						}
					}else{
						logd("DEV_FACE f="+f + " f.bitmap="+f.bitmap);
						icon.setImageResource(R.drawable.dev_default_pic);
					}
				}
			}
		}
	}
	
	private void updateDevRooms(){
		mDevRoom.removeAllViews();
		HashMap<String,DEV_FACE> faceMap = (HashMap<String, DEV_FACE>)mApp.getDataManager().checkData(DataManager.F_DEVICEFACE, null);
		for(DEV_DATA d:mDevListData){
			View v = mInflater.inflate(R.layout.looked_dev_item, null);
			View item = v.findViewById(R.id.item_view);
			item.setTag(d);
			TextView name = (TextView) item.findViewById(R.id.dev_name);
			//BatteryView namebg = (BatteryView) item.findViewById(R.id.dev_name_bg);
			name.setText(d.name);
			//namebg.setBatteryPercent(d.power);
			TextView unknownType = (TextView) item.findViewById(R.id.unknown_type);
			ImageView locaType = (ImageView) item.findViewById(R.id.dev_type_loca);
			ImageView healthType = (ImageView) item.findViewById(R.id.dev_type_health);
			ImageView sportType = (ImageView) item.findViewById(R.id.dev_type_sport);
			boolean getType = false;
			
			if(DEV_DATA.isLocationDev(d.type)){
				locaType.setVisibility(View.VISIBLE);
				getType = true;
			}else{
				locaType.setVisibility(View.GONE);
			}
			
			if(DEV_DATA.isHealthDev(d.type)){
				healthType.setVisibility(View.VISIBLE);
				getType = true;
			}else{
				healthType.setVisibility(View.GONE);
			}
			
			if(DEV_DATA.isSportDev(d.type)){
				sportType.setVisibility(View.VISIBLE);
				getType = true;
			}else{
				sportType.setVisibility(View.GONE);
			}
			
			if(!getType){
				unknownType.setVisibility(View.VISIBLE);
			}else{
				unknownType.setVisibility(View.GONE);
			}
			
			DEV_FACE f = null;
			if(faceMap != null){
				f = faceMap.get(d.id);
			}
			RoundImageView icon = (RoundImageView)item.findViewById(R.id.dev_pic);
			if((f != null) && (f.bitmap != null)){
				if(f.bitmap.isRecycled()){
					logd("DEV_FACE " + d.id + " is recycled");
					icon.setImageResource(R.drawable.dev_default_pic);
				}else{
				icon.setImageBitmap(f.bitmap);
				}
			}else{
				//logd("DEV_FACE f="+f + " f.bitmap="+f.bitmap);
				icon.setImageResource(R.drawable.dev_default_pic);
			}
			
			item.setOnClickListener(new View.OnClickListener(){

				@Override
				public void onClick(View v) {
					DEV_DATA d = (DEV_DATA) v.getTag();
					logd(d.id + "clicked");
					openDeviceDetailActivity(d);
					//((BaseHomeActions)getActivity()).openCardsActivity(d.id);
				}
				
			});
			mDevRoom.addView(v);
		}
	}
	
	private void openDeviceDetailActivity(DEV_DATA dev){
		Intent i = new Intent(getActivity(),DeviceManagerActivity.class);
		i.putExtra("dev", dev);
		startActivity(i);
	}

	private String refreshing = null;
	
	private void updateRefreshFlag(String clear){
		if(refreshing.contains(clear)){
			String[] ss = refreshing.split(":");
			String flag = "";
			for(String s:ss){
				if(s.equalsIgnoreCase(clear) == false){
					if(flag.equals("") == false){
						flag += ":";
					}
					flag += s;
				}
			}
			if(flag.trim().isEmpty())
				refreshing = null;
			else{
				refreshing = flag.trim();
			}
		}
	}
	
	
	
	public void enterTodo(String rid){
		ArrayList<TODO_DATA> arr = ((HomeActivity)getActivity()).getToDoArray();
		if((arr == null) || (arr.size() == 0)) 
			return;
		
		for(TODO_DATA d:arr){
			if(d.rid.equals(rid)){
				((BaseHomeActions)getActivity()).openToDoActivity(d);
				break;
			}
		}
	}
	
	public void dataUpdate(Intent i){
		String action = i.getAction();
		if(action.equals(DataManager.DATA_UPDATE_ACTION)){
			String t = i.getStringExtra("type");
			boolean s = i.getBooleanExtra("state", false);
			logd("dataUpdate:"+t+";"+s + "refreshing = "+refreshing);
			if(t.equals(DataManager.F_USERDATA) || t.equals(DataManager.F_USERFACE)
					|| t.equals(DataManager.F_DEVICELIST) || t.equals(DataManager.F_DEVICEFACE)){
				if(refreshing != null){
					updateRefreshFlag(t);
					if(refreshing == null){
						updateData();
						cancelRefresh();
						updateViews();
						updateTODO();
					}
				}else if(s){
					if(t.equals(DataManager.F_DEVICEFACE)){
						String tid = i.getStringExtra("tid");
						updateDevFaceOnly(tid);
					}else{
						updateData();
						updateViews();
						if(t.equals(DataManager.F_DEVICELIST)){
							updateTODO();//device name maybe changed
						}
					}
				}
			}else if(t.equals(DataManager.F_FAMILYLIST)){
				updateTODO(); // family name maybe changed
			}else if(t.equals(DataManager.F_TODO)){
				updateTODO();
			}
		}
	}
	
	private void retrieveUserData(){
		mData = (JSONObject) mApp.getDataManager().checkData(DataManager.F_USERDATA, null);
		if(mData != null){
			try {
				long t = mData.getLong("uptime");
				uptime = Math.max(uptime, t);
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
	private void retrieveDeviceListData(){
		JSONObject devjson = (JSONObject) mApp.getDataManager().checkData(DataManager.F_DEVICELIST, null);
		if(devjson != null){
			try{
				long t = devjson.getLong("uptime");
				uptime = Math.max(uptime, t);
				JSONArray ar = devjson.getJSONArray("array");
				int len = ar.length();

				mDevListData.clear();
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					DEV_DATA d = new DEV_DATA();
					d.id = e.getString("tid");
					//d.fid = e.getString("fid");
					d.name = e.getString("name");
					
					String ss = e.getString("status");
					d.status = Integer.parseInt(ss);
					
					d.type = e.getString("type");
					
					String a = e.getString("admin");
					d.admin = Integer.parseInt(a);				
					
					mDevListData.add(d);
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	
	private void updateViews(){
		int lv = 0;
		
		if(!attached)
			return;
		
		if(mAccount == null)
			return;
		
		if(mData == null){
			String n = mApp.getUserName();
			if(mApp.isMobileNumber(n)){
				n = mApp.numberToHidenString(n);
			}
			mAccount.setText(n);
			mNick.setText(R.string.noName);
			setDataLevelViews(0);
			return;
		}
		
		Bitmap bitmap = (Bitmap) mApp.getDataManager().checkData(DataManager.F_USERFACE, null);

		try {
			if((bitmap != null) && !bitmap.isRecycled()){
				mPic.setImageBitmap(bitmap);
				mPic.setType(RoundImageView.TYPE_ROUND);				
				mPic.setBackgroundColor(getResources().getColor(R.color.TRANSPARENT));
			}else{
				mPic.setImageResource(R.drawable.default_photo);
				mPic.setType(RoundImageView.TYPE_RECT);
				mPic.setBackgroundResource(R.drawable.photo_bg);
			}
			
			String ac = mData.getString("ac");
			if(ac.isEmpty()){
				ac = mApp.getUserName();
				if(mApp.isMobileNumber(ac)){
					ac = mApp.numberToHidenString(ac);
				}
			}
			mAccount.setText(ac);
			
			String mobile = mData.getString("mobile");
			
			String nick = mData.getString("nick");
			if((nick == null) || nick.isEmpty()){
				ac = mData.getString("ac");
				if(ac.isEmpty()){
					ac = mApp.getUserName();
					if(mApp.isMobileNumber(ac)){
						mNick.setText(R.string.noName);
					}else{
						mNick.setText(ac);
					}
				}else{
					mNick.setText(ac);
				}
			}else{
				mNick.setText(nick);
				lv ++;
			}
			String gender = mData.getString("gender");
			if((gender != null) && (!gender.isEmpty()) && (!gender.equalsIgnoreCase("u"))){
				lv ++;
			}
			
			String city = mData.getString("city");
			String addr = mData.getString("addr");
			if(((city != null) && (false == city.isEmpty()))
			    || ((addr != null) && (false == addr.isEmpty()))){
				lv ++;
			}
			
			String edu = mData.getString("edu");
			if((edu != null) && (false == edu.isEmpty())){
				lv ++;
			}
			
			String idcard = mData.getString("idcard");
			if((idcard != null) && (false == idcard.isEmpty())){
				lv ++;
			}
			
			if((nick == null) || nick.isEmpty()){
				if(lv > 0)
					lv --;
			}
			setDataLevelViews(lv);
			
			updateDevList();
			
			refresh.setUpdateTime(uptime);
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean cancelRefresh(){
		refreshing = null;
		if((refresh != null) && refresh.isRefreshing()){
			refresh.stopRefreshing();
			return true;
		}
		return false;
	}
	
	@Override
	public void setFocused(boolean set){
		logd("setFocused "+set);
		if(set == false){
			cancelRefresh();
		}
		super.setFocused(set);
	}
	
	@Override
	public void onResume(){
		logd("onResume");
		super.onResume();
		updateData();
		updateViews();
		updateTODO();
	}

	@Override
	public void onPause(){
		logd("onPause");
		super.onPause();
		//setFocused(false);
	}
	
	@Override
	public void onDestroyView(){
		logd("onDestroyView");
		super.onDestroyView();
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.scan:{
			//((BaseHomeActions)getActivity()).openQRScanerWin();
			((BaseHomeActions)getActivity()).openPopMenu("account",scanView);
		}
		break;
		case R.id.set:{
			((BaseHomeActions)getActivity()).openSettings("account","");
		}
		break;
		case R.id.myname:
		/*case R.id.my_data:*/{
			if(mData != null){
				((BaseHomeActions)getActivity()).openUserDetail("my_data");
			}
		}
		break;
		}
	}
}
